<?php

	class TaxonomiesController extends AppController
	{
		var $name = 'Taxonomies';
		var $uses = array('Taxonomy', 'ProductTaxonomy');
		
		var $publicAction = array('index', 'details', 'categoryList', 'widgetCategories');
		
		var $type = 'category';
		
		function index() {
			$categories = $this->Taxonomy->find(
				'all',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.disabled' => 0,
						'Taxonomy.deleted' => 0,
					),
					'contain' => array(
						'Term' => array(
							'slug'
						)
					),
					'recursive' => 0
				)
			);
			
			$this->set(compact('categories'));
			
			$this->pageTitle = __('Categorías: %s', true);
		}
		
		function details() {
			$this->helpers[] = 'Number';
			
			if (empty($this->params['slug'])) {
				$this->Session->setFlash(__('Debes seguir solo las url que se indica en la web.', true), null, array('class' => 'warning'));
				$this->redirect(array('shop' => Configure::read('Shop.slug'), 'controller' => 'shops', 'action' => 'index'));
			}
			
			$this->Taxonomy->Behaviors->attach('Containable');
			$data = $this->Taxonomy->find(
				'first',
				array(
					'conditions' => array(
						'Term.slug' => $this->params['slug'],
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.disabled' => 0,
						'Taxonomy.deleted' => 0
					),
					'contain' => array(
						'Term'
					),
					'recursive' => 0
				)
			);
			
 			// 
			if (empty($data)) {
				$this->redirect(array('shop' => Configure::read('Shop.slug'), 'controller' => 'taxonomies', 'action' => 'index'));
			}
			
			$this->pageTitle = $data['Taxonomy']['name'];
			
			$this->ProductTaxonomy->Behaviors->attach('Containable', array('autoFields' => false));
			
			$this->paginate = array(
				'conditions' => array(
					'ProductTaxonomy.taxonomy_id' => $data['Taxonomy']['id'],
					'ProductTaxonomy.disabled' => 0,
					'ProductTaxonomy.deleted' => 0
				),
				'fields' => array(
				),
				'contain' => array(
					'Product' => array(
						'fields' => array(
							'Product.id',
							'Product.price',
							'CONCAT(\''. Configure::read('Minicatalogo.url') . 'images/products/' . $this->params['shop'] . '/' .'\', REPLACE(Product.preview,\'.\',\'_preview.\')) AS preview',
						),
						'Currency' => array(
							'code',
							'symbol_left',
							'symbol_right',
							'decimal_places',
							'decimals',
							'thousands'
						),
						'ProductDescription' => array(
							'name',
							'slug'
						)
					)
				),
				'recursive' => 1
			);
			
			$products = $this->paginate('ProductTaxonomy');
			
			$this->set(compact('products'));
		}
				
		function categoryList($categories = array()) {
			foreach($categories AS $category) {
				if (!empty($category['children'])) {
					$this->categoryList($category['children']);
				}
			}
		}
		
		function widgetCategories() {
			$taxonomies = $this->Taxonomy->find(
				'threaded',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.disabled' => 0,
						'Taxonomy.taxonomy' => 'category'
					),
					'fields' => array(
						'Taxonomy.id',
						'Taxonomy.parent_id',
						'Taxonomy.name'
					),
					'contain' => array(
						'Term' => array(
							'fields' => array(
								'Term.slug'
							)
						)
					),
					'recursive' => 0
				)
			);
			return $taxonomies;
		}
		
		/*
		 * Dashboard Method
		 */
		function dashboard_index() {
			$this->pageTitle = __('Categorías', true);
			
			$this->helpers[] = 'Dashboard';
			
			$taxonomies = $this->Taxonomy->find(
				'threaded',
				array(
					'conditions' => array(
						'Taxonomy.shop_id' => Configure::read('Shop.id'),
						'Taxonomy.deleted' => 0,
						'Taxonomy.taxonomy' => 'category'
					),
					'fields' => array(
						'Taxonomy.id',
						'Taxonomy.parent_id',
						'Taxonomy.name',
						'Taxonomy.disabled'
					),
					'recursive' => -1
				)
			);
			
			$this->set(compact('taxonomies'));
		}
		
		function dashboard_add($parent_id = 0) {
			$this->pageTitle = __('Agregar categoría', true);

			if (!empty($this->data)) {
				return $this->create();
			}
			
			if (empty($this->params['isAjax'])) {
				$this->set('taxonomies', $this->Taxonomy->categories());
				
				$this->data['Taxonomy'] = compact('parent_id');
				$this->render('dashboard_form');
			}
		}
		
		function dashboard_edit($id = 0, $idEncrypt = null) {
			$this->pageTitle = __('Editar categoría', true);
			
			if (!empty($this->data)) {
				$this->data['Taxonomy']['shop_id'] = Configure::read('Shop.id');
				$this->create();
			}
			else {
				$this->Taxonomy->recursive = -1;			
				$this->data = $this->Taxonomy->find(
					'first',
					array(
						'conditions' => array(
							'id' => $id,
							'shop_id' => Configure::read('Shop.id')
						)
					)
				);
			}
			
			$this->set('taxonomies', $this->Taxonomy->categories());
			
			$this->render('dashboard_form');
		}

		function dashboard_delete($id = null, $idEncrypt = null)
		{
			$response = array();
			if (Security::hash($id, 'md5', true) != $idEncrypt) {
				if (!empty($this->params['isAjax'])) {
					$response = array(
						'type' => 'error',
						'message' => __('Es imposible hacer la acción que intentas.', true)
					);
				} else {
					$this->Session->setFlash(__('Es imposible hacer la acción que intentas.', true), null, array('class' => 'error'));
					$this->redirect(array('shop' => Configure::read('Shop.slug'), 'controller' => 'taxonomies', 'action' => 'dashboard_index'));
				}
			}
			
			$delete = $this->Taxonomy->updateAll(
				array(
					'Taxonomy.deleted' => 1
				),
				array(
					'Taxonomy.shop_id' => Configure::read('Shop.id'),
					'Taxonomy.id' => $id
				)
			);
			
			if (!empty($this->params['isAjax'])) {
				if ($delete) {
					$response = array(
						'type' => 'success',
						'message' => __('La categoría a sido eliminada exitosamente.Recuerda, los productos asociados a la categoría no se eliminarón, pero no se mostrarán en la tienda.', true)
					);
				} else {
					$response = array(
						'type' => 'error',
						'message' => __('La categoría no pudo ser eliminada, intentalo más tarde.', true)
					);
				}
			} else {
				if ($delete) {
					$this->Session->setFlash(__('La categoría a sido eliminada exitosamente, recuerda que los productos asociados a la categoría no se eliminarón, pero no se mostrarán en la tienda.', true), null, array('class' => 'error'));
				} else {
					$this->Session->setFlash(__('La categoría no pudo ser eliminada, intentalo más tarde.', true), null, array('class' => 'error'));
				}
				$this->redirect(array('controller' => 'categories', 'action' => 'index'));
			}

			$this->set('response', json_encode($response));
		}

		function getByParent($taxonomy_id = null) {
			$request = array();
			if (!is_null($category_id)) {
				$request = $this->Taxonomy->find(
					'list',
					array(
						'conditions' => array(
							'Taxonomy.parent_id' => $taxonomy_id
						)
					)
				);
			}
			
			$this->set('request', json_encode($request));
		}
		
		function create() {
			$request = array();
			if ($this->Taxonomy->validates($this->data)) {
				$this->autoRender = false;
				
				$this->data['Taxonomy']['taxonomy'] = $this->type;
				$this->data['Taxonomy']['shop_id'] = Configure::read('Shop.id');

				if ($this->Taxonomy->save($this->data)) { // guardo exitosamente.
					if (!empty($this->params['isAjax'])) {
						$request+= array(
							'status' => 'success',
							'taxonomy_id' => $this->Taxonomy->id,
							'taxonomy_id_md5' => Security::hash($this->Taxonomy->id, 'md5', true),
							'taxonomy_name' => $this->data['Taxonomy']['name']
						);
					}
					else {
						$this->Session->setFlash(__('Se ha guardado exitosamente la categoría.', true), null, array('class' => 'success'));
						if ($this->layout != 'iframe') {
							$this->redirect(array('controller' => 'taxonomies', 'action' => 'dashboard_index'));
						}
					}
				}
				else { // no se puede guardar ya que existe.
					if (!empty($this->params['isAjax'])) {
						$request+= array(
							'status' => 'failed',
							'message' => __('La categoría ingresada ya existe en tu lista.', true)
						);
					}
					else {
						$this->Session->setFlash(__('La categoría ingresada ya existe en tu lista, intenta con otra.', true), null, array('class' => 'warning'));
					}
				}
				return htmlspecialchars(json_encode($request), ENT_NOQUOTES);
			} // else ... faltan datos para guardar la categoría.
		}
		
		private function save($parent_id = 0)
		{
			$taxonomy_exists_msg = __('La categoría ingresada ya existe en tu lista.', true);
			$taxonomy_save_success_msg = __('Se ha realizado la acción exitosamente.', true);
			
			$taxonomy_exists = $this->Taxonomy->hasAny(
				array(
					'Taxonomy.shop_id' => Configure::read('Shop.id'),
					'Taxonomy.deleted' => 0,
					'Taxonomy.parent_id' => $parent_id,
					'Taxonomy.name' => $this->data['Taxonomy']['name']
				)
			);
			
			$request = array();
				
			if ($taxonomy_exists) {
				if ($this->params['isAjax']) {
					$request['status'] = 'error';
					$request['message'] = $taxonomy_exists_msg;
				}
				else {
					$this->Session->setFlash($taxonomy_exists_msg, null, array('class' => 'red'));
					if ($this->layout != 'iframe') {
						$this->redirect(array('shop' => $this->params['shop'], 'controller' => 'taxonomies', 'action' => 'dashboard_index'));						
					}
				}
			}
			else {
				$data = $this->Taxonomy->Term->find(
					'first',
					array(
						'conditions' => array(
							'Term.deleted' => 0,
							'Term.name' => $this->data['Taxonomy']['name']
						),
						'fields' => array(
							'Term.id'
						),
						'recursive' => -1
					)
				);
				
				if (!empty($data)) {
					$id_term = $data['Term']['id'];
				}
				else {
					$this->data['Term']['name'] = $this->data['Taxonomy']['name'];
					$this->data['Taxonomy']['slug'] = $this->data['Term']['slug'] = strtolower(Inflector::slug($this->data['Taxonomy']['name'], '-'));
					$this->Taxonomy->Term->save($this->data);
					$id_term = $this->Taxonomy->Term->id;
				}
				
				$this->data['Taxonomy']['parent_id'] = $parent_id;
				$this->data['Taxonomy']['shop_id'] = Configure::read('Shop.id');
				$this->data['Taxonomy']['term_id'] = $id_term;
				//$this->data['Taxonomy']['name'] = $this->data['Term']['name'];
				$this->data['Taxonomy']['taxonomy'] = 'category';
				
				$this->Taxonomy->Behaviors->detach('Tree');
				
				$this->Taxonomy->id = null;
				$this->Taxonomy->save($this->data);
				
				if ($this->params['isAjax']) {
					$request['status'] = 'success';
					$request['message'] = $taxonomy_save_success_msg;
					$request['taxonomy_id'] = $this->Taxonomy->id;
					$request['taxonomy_id_md5'] = Security::hash($this->Taxonomy->id, 'md5', true);
					$request['taxonomy_name'] = $this->data['Taxonomy']['name'];
				}
				else {
					$this->Session->setFlash($taxonomy_save_success_msg, null, array('class' => 'success'));
					if ($this->layout != 'iframe') {
						$this->redirect(array('shop' => $this->params['shop'], 'controller' => 'taxonomies', 'action' => 'dashboard_index'));
					}
				}
			}
			if ($this->params['isAjax']) {
				return $request;
			}
		}
	}

?>